package com.coinread.hr.tools.service.impl;

import com.coinread.hr.tools.bean.persistence.AdminService;
import com.coinread.hr.tools.common.JwtToken;
import com.coinread.hr.tools.service.MailService;
import com.coinread.hr.tools.service.UserService;
import com.coinread.hr.tools.utils.CookieUtils;
import com.coinread.hr.tools.utils.HtmlUtils;
import com.coinread.hr.tools.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

/**
 * @Author ：yaxuSong
 * @Description:
 * @Date: 17:39 2018/6/25
 * @Modified by:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private MailService mailService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private HttpServletResponse response;

    @Value("${spring.mail.username}")
    private String sender;

    @Override
    public int login(String user, String pwd) throws Exception {
        if (user.equals(sender)){
            String title = "HR-TOOLS登录提示" ;
            JavaMailSender javaMailSender = MailUtils.initJavaMailSender(sender,pwd);
            int res = mailService.send(HtmlUtils.genHtmlVerifyContent(getMesage(),title),title,user,user,pwd);
            if (res==1) {
                adminService.setPass(pwd);
                CookieUtils.writeCookie(response,"sessionJd",JwtToken.createToken(user));
                return 1;
            }
        }
        return 0;
    }

    private String getMesage(){
        Calendar calendar = Calendar.getInstance();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        return "您在北京时间："+date+" 使用了当前邮箱登录了HR-tools系统。";
    }

}
